﻿# MySQL服务监控守护脚本
# 每30秒检查MySQL服务，如果停止则自动重启

$serviceName = "MySQL80"
$logDir = "E:\DEV_VISION\logs"
$logFile = "$logDir\mysql_watchdog.log"

# 创建日志目录
if (-not (Test-Path $logDir)) {
    New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}

function Write-Log {
    param([string]$Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[] $Message"
    Write-Host $logEntry -ForegroundColor Cyan
    Add-Content -Path $logFile -Value $logEntry
}

function Test-AdminRights {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

Write-Log "MySQL监控守护进程启动"

if (-not (Test-AdminRights)) {
    Write-Log "警告: 运行在非管理员权限下，可能无法重启服务"
}

while ($true) {
    try {
        $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
        
        if (-not $service) {
            Write-Log "错误: 未找到MySQL服务 $serviceName"
            Start-Sleep -Seconds 60
            continue
        }
        
        if ($service.Status -ne 'Running') {
            Write-Log "检测到MySQL服务已停止 (状态: $($service.Status))，尝试重启..."
            
            if (Test-AdminRights) {
                try {
                    Start-Service -Name $serviceName -ErrorAction Stop
                    Start-Sleep -Seconds 3
                    $service.Refresh()
                    
                    if ($service.Status -eq 'Running') {
                        Write-Log "✅ MySQL服务重启成功"
                    } else {
                        Write-Log "❌ MySQL服务重启失败，当前状态: $($service.Status)"
                    }
                } catch {
                    Write-Log "❌ 重启MySQL服务时发生错误: $($_.Exception.Message)"
                }
            } else {
                Write-Log "❌ 缺少管理员权限，无法重启服务"
            }
        }
    } catch {
        Write-Log "监控过程中发生错误: $($_.Exception.Message)"
    }
    
    Start-Sleep -Seconds 30
}
